//
//  ST_GiftViewController.swift
//  btvideo
//
//  Created by mac on 2020/6/28.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import SnapKit
import MBProgressHUD
import NIMSDK
import SwiftyAttributes
import SwiftyUserDefaults
import RxCocoa
import RxSwift


var GIFT_NUMBER:Int = 1{
    didSet{
        CURR_GIFT_ITEM_CELL?.refresh_gift_number()
    }
}

weak var CURR_GIFT_ITEM_CELL:ST_GiftItemView?

class ST_GiftViewController: UIViewController,ST_TIANPaymentTransactionStateDelegate{
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
         
        
        layout_u_i()
        
        binding()
    }
    
    fileprivate func binding(){
        
        segment_control.isUserInteractionEnabled = false
        
        viewModel.fetchGiftListSession().withUnretained(self).subscribe(onNext: { own,result in
            
            own.segment_control.isUserInteractionEnabled = true
            
            switch result {
            case .success:
                
                own.last_selected_control_model = own.viewModel.selectFirstGift()
                
                own.collectionView.reloadData()
                
                if let first = own.viewModel.data_array.first{
                    own.pageControl.numberOfPages = first.pages
                    own.pageControl.currentPage = 0
                    
                    own.pageControl.isHidden = own.pageControl.numberOfPages < 2
                }
                
            case .failure(let err):
                own.toast(text: err.e)
            }
            
        }).disposed(by: disposeBag)
        
        
        pull_intimacy()
    }
    
    fileprivate func pull_intimacy(){
        
        JVrequest(PH.currIntimacyProgressApi,parameters: ["target_accid":self.userId]) { (json) in
            
            self.current_intimacy_btn.setTitle(" " + json["data"]["next_intimacy"]["name"].stringValue, for: UIControl.State.normal)
            
            self.current_intimacy_btn.pin_setImage(from: json["data"]["next_intimacy"]["image"].stringValue.compress_small_image(width: 17).url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
            
            let curr = json["data"]["current_intimacy"].floatValue
            
            let total = json["data"]["total_intimacy"].floatValue
            
            if total == 0{
                self.current_intimacy_progress_view.playPercent(progress: 0)
            }else{
                self.current_intimacy_progress_view.playPercent(progress: curr.cgFloat/total.cgFloat)
            }
            
            
            print("bug 000189891:\(Date()) 当前=",curr,"----total=",total)
            
        } failure: { (code, error) in
            
            self.toast(text: error)
        }
    }
    
    fileprivate func layout_u_i(){
        
        view.addSubview(root_view)
        root_view.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(16)
            make.height.equalTo(gift_container_height+58+71+16+BTSafeAreaBottom+83)
        }
        
        view.addSubview(close_view)
        close_view.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
            make.bottom.equalTo(root_view.snp.top)
        }
        
        root_view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(20)
            make.height.equalTo(20)
        }
        
        
        root_view.addSubview(current_intimacy_btn)
        current_intimacy_btn.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.height.equalTo(17)
            make.top.equalTo(titleLabel.snp.bottom).offset(11)
        }
        
        root_view.addSubview(push_next_intimacy_btn)
        push_next_intimacy_btn.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(39)
            make.top.equalTo(titleLabel.snp.bottom)
        }
        
        root_view.addSubview(current_intimacy_progress_view)
        current_intimacy_progress_view.snp.makeConstraints { (make) in
            make.height.equalTo(5)
            make.left.equalTo(current_intimacy_btn.snp.right).offset(10)
            make.right.equalTo(push_next_intimacy_btn.snp.left).offset(-10)
            make.centerY.equalTo(current_intimacy_btn)
        }
        
        
        
        root_view.addSubview(segment_control)
        segment_control.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(15-6+83)
            make.height.equalTo(ST_GitSegmentControl.height)
        }
        
        root_view.addSubview(queryBtn)
        queryBtn.snp.makeConstraints { make in
            make.centerY.equalTo(segment_control)
            make.right.equalToSuperview().offset(-20)
        }
        
        //        segment_control.backgroundColor = .random
        
        root_view.addSubview(collectionView)
        collectionView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(segment_control.snp.bottom).offset(5)
            make.height.equalTo(gift_container_height+10)
        }
        
        root_view.addSubview(pageControl)
        
        pageControl.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(collectionView.snp.bottom).offset(1)
            make.height.equalTo(5+10)
            //            make.width.equalTo(100)
        }
        
        
        root_view.addSubview(giveBtn)
        root_view.addSubview(recharge_btn)
        giveBtn.snp.makeConstraints { (make) in
            make.width.equalTo(78)
            make.height.equalTo(34)
            make.bottom.equalToSuperview().offset(-BTSafeAreaBottom-10-16)
            make.right.equalToSuperview().offset(-15)
        }
        
        recharge_btn.snp.makeConstraints { (make) in
            make.centerY.equalTo(giveBtn)
            make.left.equalToSuperview().offset(15)
        }
        
        root_view.addSubview(number_options_button)
        number_options_button.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(26)
            make.centerY.equalTo(segment_control)
        }
        
            
        if let m = SC.numberOptions.last{
            selected_number = m
        }
    
        
        create_supplement_container_view()
        
        segment_control.titleArray = viewModel.tabTitleArray
        
        
        
        
        
        segment_control.selected_closure = {[weak self] idx in
            
            guard let indexPath = self?.viewModel.indexPathOf(tabIndex: idx) else{
                return
            }
            
            self?.collectionView.setContentOffset(CGPoint.init(x: ScreenWidth*indexPath.row.cgFloat, y: -10), animated: true)
            
            guard let currItemModel = self?.viewModel.data_array[safe:indexPath.row] else{
                return
            }
            
            self?.recharge_btn.isHidden = currItemModel.indexOfTab == 2
            self?.pageControl.numberOfPages = currItemModel.pages
            self?.pageControl.currentPage = 0
            self?.pageControl.isHidden = currItemModel.pages < 2
            
        }
    }
    
    fileprivate func create_supplement_container_view(){
        
        self.view.addSubview(supplement_container_view)
        supplement_container_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(155)
            make.bottom.equalTo(root_view.snp.top).offset( iPhoneXSeries ? -40 : -20)
            make.centerX.equalToSuperview()
        }
        
        supplement_container_view.addSubview(icon)
        icon.snp.makeConstraints { (make) in
            make.width.height.equalTo(115)
            make.center.equalToSuperview()
        }
        
        supplement_container_view.addSubview(icon_supplement_image_view)
        icon_supplement_image_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
    }
    
    //    MARK:- properties
    var disposeBag = DisposeBag()
    
    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel.init()
        control.text = "送Ta礼物，开启亲密成长之旅！"
        control.textColor = UIColor(hexString: "#FEC207")
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
        return control
    }()
    
    
    fileprivate lazy var current_intimacy_progress_view:ST_IntimacyProgressItemView = {
        let control = ST_IntimacyProgressItemView()
        control.cornerRadius = 2
        return control
    }()
    
    fileprivate lazy var current_intimacy_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.medium)
//        control.semanticContentAttribute = .forceRightToLeft
        return control
    }()
    
    fileprivate lazy var push_next_intimacy_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 12, weight: UIFont.Weight.regular)
        control.semanticContentAttribute = .forceRightToLeft
        control.setTitle("查看详情", for: UIControl.State.normal)
        control.setImage(ST_ImageUtils.imageName("下一页_tiny"), for: UIControl.State.normal)
        control.addTarget(self, action: #selector(infoHandle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var icon:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.cornerRadius = 115/2.0
        control.imageView?.contentMode = .scaleAspectFill
        control.clipsToBounds = true
        return control
    }()
    
    fileprivate lazy var icon_supplement_image_view:UIImageView = {
        let control = UIImageView()
        return control
    }()
    
    fileprivate lazy var supplement_container_view:UIView = {
        let control = UIImageView()
        control.alpha = 0
        return control
    }()
    
    
    
    fileprivate lazy var root_view:UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.init(hex: 0x202223)
        control.cornerRadius = 16
        return control
    }()
    
    fileprivate lazy var close_view:UIButton = {
        let control = UIButton()
        control.addTarget(self, action: #selector(closeHanlde), for: UIControl.Event.touchUpInside)
        return control
    }()
    @objc fileprivate func closeHanlde(){
        
        last_selected_control_model?.isSelected = false
        
        self.goback_previous_controller()
    }
    
    fileprivate lazy var segment_control:ST_GitSegmentControl = {
        let control = ST_GitSegmentControl()
        return control
    }()
    
    fileprivate lazy var queryBtn:UIButton = {
        let btn = UIButton.init(type: UIButton.ButtonType.custom)
        btn.setImage(ST_ImageUtils.imageName("blind_box_query_icon"), for: .normal)
        btn.addTarget(self, action: #selector(query_btn_click), for: UIControl.Event.touchUpInside)
        btn.alpha = 0
        return btn
    }()
        
    
    fileprivate var selected_number:ST_GiftNumberStruct?{
        didSet{
            
            GIFT_NUMBER = selected_number?.number ?? 1
            
            if let m = selected_number{
                let str = m.number.string + "个"
                number_options_button.setTitle(str.withAttributes([Attribute.font(.systemFont(ofSize: 12, weight: .medium)),.textColor(#colorLiteral(red: 0.9960784314, green: 0.7607843137, blue: 0.02745098039, alpha: 1))]), for: .normal)
                
            }
        }
    }
    fileprivate weak var giftNumberVC:ST_GiftNumbersController?
    fileprivate lazy var number_options_button:ST_TianButton = {
        let control = ST_TianButton(style: ST_TianButtonStyle.title_left_image_right(titleLeft: 5, imageSize: CGSize(width: 12, height: 12), layout: ST_TianButtonLayoutModel.inside_auto_resize(relevantOffset: 12, lastControlEdgeValue: -5)))
        control.cornerRadius = 5
        control.borderColor = #colorLiteral(red: 1, green: 0.7970786095, blue: 0, alpha: 1)
        control.borderWidth = 1
        control.setImage(ST_ImageUtils.imageName("arrow_icon_up"), for: UIControl.State.selected)
        control.setImage(ST_ImageUtils.imageName("arrow_icon_down"), for: UIControl.State.normal)
        control.addTarget(self, action: #selector(pick_number_handle), for: .touchUpInside)
        return control
    }()
    
    fileprivate lazy var gift_container_height = ST_GiftItemView.height*2+ST_GiftItemView.gap
    
    fileprivate lazy var layout:UICollectionViewFlowLayout = {
        let controlLayout = UICollectionViewFlowLayout()
        controlLayout.scrollDirection = .horizontal
        controlLayout.minimumLineSpacing = 0
        controlLayout.minimumInteritemSpacing = 0
        controlLayout.itemSize = CGSize.init(width: ScreenWidth, height: gift_container_height)
        return controlLayout
    }()
    
    
    fileprivate lazy var collectionView:UICollectionView = {
        let control = UICollectionView.init(frame: CGRect.zero, collectionViewLayout: self.layout)
        control.isPagingEnabled = true
        control.backgroundColor = Color.clear
        control.contentInset = UIEdgeInsets(top: 10, left: 0, bottom: 0, right: 0)
//        control.backgroundColor = .random
        control.delegate = self
        control.dataSource = self
        //        control.alwaysBounceVertical = true
        
        control.register(cellWithClass: ST_GiftTabCell.self)
        control.register(cellWithClass: ST_GiftMemberTabCell.self)
        
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        if #available(iOS 11.0, *) {
            control.contentInsetAdjustmentBehavior = .never
        }
        return control
    }()
    
    fileprivate weak var last_selected_control_model:ST_BTGiftModel?{
        didSet{
            
            guard let m = last_selected_control_model else{
                self.supplement_container_view.alpha = 0
                return
            }
            
            if m.tabType == .gift && m.isBlindBox == false{
                self.number_options_button.alpha = 1
            }else{
                self.number_options_button.alpha = 0
            }
            
            queryBtn.alpha = m.isBlindBox ? 1 : 0
            
            if m.tabType == .sweetGuard{
                
                self.supplement_container_view.alpha = 1
                
                self.icon_supplement_image_view.pin_setImage(from: m.imageUrl.url)
                
            }else{
                self.supplement_container_view.alpha = 0
            }
            
        }
    }
    
    fileprivate lazy var viewModel = ST_GiftViewModel()
    
    
    fileprivate lazy var pageControl:UIPageControl = {
        let control = UIPageControl()
        control.pageIndicatorTintColor = UIColor.init(hex: 0xACB4C0)
        control.currentPageIndicatorTintColor = UIColor.init(hex: 0xFEC207)
        //        control.addTarget(self, action: #selector(changePage(sender:)
        //            ), for: UIControl.Event.touchUpInside)
        control.isUserInteractionEnabled = false
        
        //        control.backgroundColor = .random
        return control
    }()
    
    fileprivate lazy var giveBtn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleForAllStates("赠送")
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)
        control.backgroundColor = Color.init(hexString: "#FEC207")
        control.setTitleColorForAllStates(UIColor.init(hex: 0x202223)!)
        control.cornerRadius = 17
        control.addTarget(self, action: #selector(give_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var recharge_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        control.setTitleForAllStates("马上充值")
        control.setTitleColorForAllStates(Color.init(hexString: "#FEC207")!)
        
        control.setImageForAllStates(ST_ImageUtils.imageName("个人中心_icon_下一页_orange")!)
        
        control.semanticContentAttribute = .forceRightToLeft
        control.addTarget(self, action: #selector(recharge_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate var give_member:BTMemberGoodsModel?
    
    var goods_presented:((ST_BTIMGiftMessageModel)->())?
    
    var userId = ""
    
    var avatar = ""{
        didSet{
            icon.pin_setImage(from: avatar.compress_small_image(width: 200).url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
        }
    }
    
    var displayToast = true
    
    fileprivate var lastPage = 0
}

extension ST_GiftViewController{
    
    
    @objc private func query_btn_click(){
        
        guard let m = last_selected_control_model,let urlStr = m.skipUrl,let titleStr = m.skipTitle else{
            return
        }
        
        let vc = ST_BTWebViewController()
        
        vc.urlStr = urlStr
        
        vc.titleStr = titleStr
        
        GlobalPresent(toController: vc)
    }
    
    
    @objc fileprivate func pick_number_handle(){
        
        if number_options_button.isSelected {
            number_options_button.isSelected = false
            giftNumberVC?.view.removeFromSuperview()
            giftNumberVC?.removeFromParent()
            return
        }
        
        let vc = ST_GiftNumbersController.createController()
        self.addChild(vc)
        view.addSubview(vc.view)
        vc.view.snp.makeConstraints { make in
            make.top.equalTo(number_options_button.snp.bottom).offset(10)
            make.right.equalTo(number_options_button)
            make.width.equalTo(110)
            make.height.equalTo(226)
        }
        
        vc.callBack = {[weak self] m in
            
            guard let strongSelf = self else { return  }
            
            vc.view.removeFromSuperview()
            vc.removeFromParent()
            
            self?.selected_number = m
            strongSelf.number_options_button.isSelected = false
        }
        giftNumberVC = vc
        number_options_button.isSelected = true
    }
    
    @objc fileprivate func infoHandle(){
     
        GlobalPresent(toController: ST_SweetRankViewController())
        
    }
    
    func transaction_succeed() {
        
        guard let memberModel = self.give_member else { return }
        
        let goods = ST_BTIMGiftMessageModel()
        
        goods.goodsId = memberModel.limited_time.string
        
        goods.title = "送了你\(memberModel.limited_time)个月会员"
        
        goods.type = ST_IMGoodsType.give_member
        
        goods.subTitle = "亲密度+"+memberModel.intimacy.string
        
        send_goods_message(goods: goods)
        
        let vc = BTVerticalAlertViewController.createGiveMemberAlert()
        
        GlobalPresent(toController: vc)
    }
    
    @objc fileprivate func recharge_handle(){
        
        ST_RechargeViewController.toast()
        
    }
    
    @objc fileprivate func recharge_tips_handle(){
        
        
//        let alert = BTVerticalAlertViewController.createRequireRechargeAlert()
//
//        alert.confirm_closure = {[weak self] in
//
//            self?.recharge_handle()
//        }
//
//        GlobalPresent(toController: alert)
        
        
        ST_RechargeViewController.toast()
        
        self.hidden_indeterminate_h_u_d()
    }
    
    @objc fileprivate func give_handle(){
        
        
        
        guard let originalModel = last_selected_control_model else { return  }
        
        if ST_BTUserInfoManager.shared.confined_to_ticket(){
            
            let vc = ST_TicketViewController()
            
            vc.from = .mainIndexConfined
            
            GlobalPresent(toController: vc)
            
            return
        }
        
        
        self.show_indeterminate_h_u_d()
        
        if originalModel.tabType == .member{
            
            
            guard let memberModel = originalModel.give_member else {
                self.hidden_indeterminate_h_u_d()
                return
            }
            
            self.give_member = memberModel
            
            ST_MaidWayManager.shared.source = .聊天赠送
            
            ST_MaidWayManager.shared.doWay(id: memberModel.id.string, delegate: self)
            
        }else{
            
            guard let originalGoodsModel = originalModel.common ,let coin = ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sweet_coin else {
                self.hidden_indeterminate_h_u_d()
                return
            }
            
            var api = originalGoodsModel.type == GoodsType.gift ?  PH.presentSmallGiftApi : PH.presentGuardSupplementApi
            
            var expendCoin = originalGoodsModel.useCoin.float
            
            let giftNumber = self.selected_number?.number ?? 1
            
            if originalGoodsModel.type == .gift{
                expendCoin = expendCoin * giftNumber.float
            }
            
            if coin  < expendCoin{
                
                if originalGoodsModel.type == GoodsType.gift{
                    ST_MaidWayManager.shared.source = .送礼物
                }else{
                    ST_MaidWayManager.shared.source = .送守护
                }
                
                recharge_tips_handle()
                
                return
            }
            
            if originalModel.nobleWidget != nil{
                api = PH.presentNobleSmallGiftApi
            }else if originalModel.isBlindBox{
                api = PH.presentBlindBoxGiftApi
            }
            
            JVrequest(api,parameters: ["target_accid":self.userId,"id":originalGoodsModel.id ?? "","num":giftNumber.string], success: { (json) in
                
                if self.displayToast{
                    self.toast(text: "赠送成功")
                }else{
                    self.hidden_indeterminate_h_u_d()
                }
                
                var gModel = originalModel,goodsModel = originalGoodsModel
                
                /// 扣币还是按照 盲盒的消耗 扣币
                main_thread_execute {
                    ST_BTUserInfoManager.shared.modify_sweet_coin(value: coin - goodsModel.useCoin.float)
                }
                
                let isBlindBox = gModel.isBlindBox
                
                ///盲盒赠送 礼物数据来自后台 使用后台返回数据 替换 gModel 和 goodsModel
                if isBlindBox{
                    gModel = ST_BTGiftModel(json: json["data"], giftType: .gift)
                    if let m = gModel.common{
                        goodsModel = m
                    }
                }
                
                if isBlindBox{
                    
                    let animateVC:ST_OpenBlindBoxBrowser
                    
                    if let urlStr = gModel.svgaUrl,urlStr.count > 1{
                        
                        animateVC = ST_OpenBlindBoxBrowser(box: ST_DrawOutBlindBox.svga(url: urlStr.url), giftName: goodsModel.name)
                        
                    }else{
                        
                        animateVC = ST_OpenBlindBoxBrowser(box: ST_DrawOutBlindBox.normal(str: gModel.imageUrl), giftName: goodsModel.name)
                        
                    }
                    
                    animateVC.overCurrentContext = true
                    
                    animateVC.over_current_context_alpha = "0.4"
                    
                    GlobalPresent(toController: animateVC, animated: false)
                    
                    
                }else if let url = gModel.svgaUrl,url.count > 1{
                    
                    ST_GiftAnimationViewController.browserGift(imageUrl: "", svgaUrl: url)
                    
                }
                

                
                let goods = ST_BTIMGiftMessageModel()
                
                goods.goodsId = goodsModel.id.string
                goods.giftName = goodsModel.name
                goods.svgaUrl = gModel.svgaUrl
                goods.isBlindBox = isBlindBox
                //                goods.subTitle = "亲密度+"+goodsModel.intimacy.string
                var v = expendCoin/10.0
                
                if isBlindBox{
                    v = json["data"]["integral"].floatValue
                }
                
                goods.subTitle = "+\(v)\(Defaults[.PandaStr])"
                
                goods.imageUrl = gModel.imageUrl
                
                goods.income = v
                
                goods.giftNumber = giftNumber
                
                goods.intimacy = gModel.common?.intimacy ?? 0
                
                
                let logGiftId = json["data"]["member_gift_id"].stringValue
                if logGiftId.count > 0{
                    goods.logGiftId = logGiftId
                }
                
                if goodsModel.type == GoodsType.gift{
                    goods.title = "送你1个" + goodsModel.name
                    goods.type = ST_IMGoodsType.gift
                }else{
                    goods.title = goodsModel.name + "守护了你"
                    goods.type = ST_IMGoodsType.sweetGuard
                    
                    let eDate = Date().adding(Calendar.Component.day, value: 1)
                    
                    var userInfoDict = ["guardTime":eDate.timeIntervalSince1970.int,    "guardContent":gModel.imageUrl,"userId":self.userId,"effectiveTime":goodsModel.effectiveTime ?? 0] as [String : Any]
                    
                    let sortedArray = self.viewModel.dataArrayForGuide.first?.pageArray.sorted(by: { (img0: ST_BTGiftModel, img1: ST_BTGiftModel) -> Bool in
                        return img0.common?.useCoin ?? 0 < img1.common?.useCoin ?? 0
                    })
                    
                    let nextElement = sortedArray?.first(where: { (kk) -> Bool in
                        return kk.common?.useCoin ?? 0 > goodsModel.useCoin
                    })
                    
                    
                    
                    if let next = nextElement{
                        userInfoDict.updateValue(next.common?.useCoin ?? 0, forKey: "guard_next_coin")
                    }else{
                        userInfoDict.updateValue(true, forKey: "guard_is_max")
                    }
                    
                    NotificationCenter.default.post(name: Notification.Name.sendGuard, object: nil, userInfo: userInfoDict)
                    
                }
                
                self.send_goods_message(goods: goods)
                
                main_thread_execute(afterDelay: 1.5) {
                    self.pull_intimacy()
                }
                
                
            }) { (code, err) in
                
                self.hidden_indeterminate_h_u_d()
                
                if code == 10004{
                    
                    ST_RechargeViewController.toast()
                    
                }else if code == 30002{
                    
                    let alert = BTVerticalAlertViewController.createGuardAlert(title: "无法对TA守护哦", content: "她已经有人使用最高级的守护了哦~\n要不再去看看其他人吧")
                    
                    GlobalPresent(toController: alert)
                    
                }else if code == 30001{
                    
                    let alert = BTVerticalAlertViewController.createGuardAlert(title: "需要更高级的守护", content: "TA已经有人守护了哦~使用更高级的守护你\n就可以顶掉那个人，成为TA的专属守护者")
                    
                    GlobalPresent(toController: alert)
                    
                }else{
                    self.toast(text: err)
                }
                
                
            }
        }
        
        
        
    }
    @objc fileprivate func changePage(sender:UIPageControl){
        
        print("点击跳转页事件")
    }
    
    fileprivate func update_selected(item:ST_BTGiftModel){
        
        if item == last_selected_control_model{
            return
        }
        
        last_selected_control_model?.isSelected = false
        last_selected_control_model = item
        
        collectionView.reloadItems(at: collectionView.indexPathsForVisibleItems)
    }
    
    /// 滑动到下一页
    fileprivate func scrollTo(currPage:Int){
        
        guard currPage > -1,let m = viewModel.data_array[safe:currPage],lastPage != currPage else{
            return
        }
            
        lastPage = currPage
        
        if let firstItem = m.pageArray.first{
            m.pageArray.first?.isSelected = true
            self.update_selected(item: firstItem)
        }
        
        self.segment_control.selectBtn(index: m.indexOfTab)
        
        self.recharge_btn.isHidden = m.indexOfTab == 2
        self.pageControl.numberOfPages = m.pages
        self.pageControl.currentPage = m.currentPageOfTab
        self.pageControl.isHidden = self.pageControl.numberOfPages < 2
        
        
    }
    
    fileprivate func send_goods_message(goods:ST_BTIMGiftMessageModel) {
        
        var type = ST_DTChatCellStyle.goodsType
        
        switch goods.type {
        case .gift:
            type = .incomeGift
        case .sweetGuard:
            type = .incomeGuard
        default:
            break
        }
        
        let model = ST_DTChatMessage()
        
        model.chatID = self.userId
        
        model.messageTime = Int64(Date().timeIntervalSince1970)
        
        model.cellStyle = type
        
        model.direction = .send
        
        guard let account = ST_BTUserInfoManager.shared.current_account_info,let userInfo = account.userinfo else { return }
        
        model.portraitUri = userInfo.avatar
        
        model.userName = userInfo.nickname
        
        model.goods = goods
        
        model.figureFrame()
        
        //        需要扣费的 消息类型
        if  model.check_send_with_create_remote_ext(send_requre_coin: 0, source: "0") == false{
            
            return
        }
        
        ST_DTChatMessageSendHander.shared.sendMessage(message: model)
        
        goods_presented?(goods)
        
    }
    
}


extension ST_GiftViewController:UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return viewModel.data_array.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
        let model = viewModel.data_array[indexPath.row]
        
        
        if let firstItem = model.pageArray.first,firstItem.tabType == .member{
        
            let cell = collectionView.dequeueReusableCell(withClass: ST_GiftMemberTabCell.self, for: indexPath)
            
            cell.selected_closure = {[weak self] model in
                
                self?.update_selected(item: model)
            }
            
            cell.model = model
            
            return cell
        }
        
        let cell = collectionView.dequeueReusableCell(withClass: ST_GiftTabCell.self, for: indexPath)
        
        cell.model = model
        
        cell.selected_closure = {[weak self] model in
            
            self?.update_selected(item: model)
        }
        
        return cell
    }
    
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
        
        if !decelerate{
            scrollviewdidEndScroll(scrollView)
        }
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        scrollviewdidEndScroll(scrollView)
        
    }
    
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        
        
        let currPage = (scrollView.contentOffset.x/ScreenWidth).int
        
        scrollTo(currPage: currPage)
    }
    
    //    MARK: 停止滚动
    func scrollviewdidEndScroll(_ scrollView:UIScrollView){
        
        let currPage = (scrollView.contentOffset.x/ScreenWidth).int
        
        scrollTo(currPage: currPage)
    }
    
    
    
}


func GiveGoodsApnsText(goods:ST_BTIMGiftMessageModel)->String{
    
    /*
     var pushContent = ""
     switch goods.type {
     case .requireDetect:
     pushContent = "请先去完成【真人头像认证】才能继续对话哦~"
     case .sweetGuard:
     pushContent = "我用【" + goods.title + "】守护了你哟！"
     case .give_member:
     pushContent = "给你送了【" + goods.goodsId + "个月】会员哟！"
     default:
     pushContent = "给你送了一个礼物【" + goods.title + "】哟！"
     }
     
     if let nickname = ST_BTUserInfoManager.shared.current_account_info?.userinfo?.nickname {
     pushContent = nickname + "：" + pushContent
     }*/
    
    return goods.title
}





//MARK: - Other View

class ST_IntimacyProgressItemView: UIView {
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = UIColor(hex: 0x3D3E3E)
        self.addSubview(progressLine)
        progressLine.snp.makeConstraints { (make) in
            make.left.top.bottom.equalToSuperview()
            make.width.equalTo(0)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var progressLine:UIView = {
        let control = UIView()
        control.backgroundColor = UIColor(hex: 0xFEC207)
        control.cornerRadius = 2
        return control
    }()
    
    //    MARK: - public method
    func playPercent(progress:CGFloat){
        
        let w = self.bounds.width * progress
        
        print("bug 000189891:progress \(progress) --- \(w)   ---view Width:\(self.bounds.width)")
        
        progressLine.snp.remakeConstraints { (make) in
            make.left.top.bottom.equalToSuperview()
            make.width.equalToSuperview().multipliedBy(progress)
        }
        
    }
    
    
    
}

